// http://www.jianshu.com/p/4372ad69c861
// https://help.aliyun.com/document_detail/31925.html
const Base64 = require("./base64")
let Crypto = require("./crypto1/crypto")
const hmac = require("./crypto1/hmac")
Crypto = hmac(Crypto)
const sha1 = require("./crypto1/sha1")
Crypto = sha1(Crypto)

const accessid = 'LTAI4DEGXwUz76nR'
const accesskey= '9FNxHNCpgCFVY6drJbww46cHomLFn8'
const host = 'https://oss.liuzijin.com'

const sign = function (date) {
  const expires = date.toISOString()
  const policyText = {
      "expiration": expires, //该Policy的失效时间
      "conditions": [
          ["content-length-range", 0, 100 * 1024 * 1024] // 上传文件的大小限制 100m
      ]
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText))
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, { asBytes: true })
  const signature = Crypto.util.bytesToBase64(bytes)
  return {
    policyBase64,
    signature
  }
}

const uploadFile = function (key, filePath, successCB, errorCB) {
  let date = new Date()
  date.setHours(date.getHours() + 87600)
  const signResult = sign(date)

  wx.uploadFile({
    url: host,
    filePath: filePath,
    // 坑，wx.uploadFile自建表单的field name。不能随意定义，默认都是'file'
    // https://segmentfault.com/a/1190000008352305
    name: 'file',
    formData: {
      'key': key,
      'OSSAccessKeyId': accessid,
      'policy': signResult.policyBase64,
      'signature': signResult.signature,
      'success_action_status': '200',
    },
    success: function (res) {
      if (res.statusCode != 200) {
        errorCB(res)
        return
      }
      successCB(key)
    },
    fail: function (err) {
      err.wxaddinfo = host
      errorCB(err)
    }
  })
}

const downloadFile = function (key, successCB, errorCB) {
  // https://help.aliyun.com/document_detail/31952.html
  // let date = new Date()
  // date.setHours(date.getHours() + 87600)
  // const signResult = sign(date)

  wx.downloadFile({
    url: `${host}/${key}`,
    // url: `${host}/${key}/OSSAccessKeyId=${accessid}&Expires=${date.getTime()}&Signature=${signResult.signature}`,
    success: function(res) {
      if (res.statusCode != 200) {
        errorCB(res)
        return
      }
      successCB(res.tempFilePath)
    },
    fail: function (err) {
      err.wxaddinfo = host
      errorCB(err)
    }
  })
}

module.exports = {
  uploadFile,
  downloadFile
}